﻿#include "intercomProxy.h"
#include <QJsonObject>
#include <QJsonDocument>
#include "logfile.h"

IntercomProxy::IntercomProxy(int port, QObject *parent) :
    QObject(parent),
    m_cfg()
{
    m_listenPort = port;
    m_server = new HttpServer(QString("IntercomProxy"));
    if(Q_NULLPTR == m_server)
    {
        QString strLog = "create Http_server fail!";
        logFile::printLog(strLog);
        return;
    }

    connect(m_server, SIGNAL(sigHttpReqData(QString,QByteArray)),
            this, SLOT(onGetOpenDoorData(QString,QByteArray)));
}

IntercomProxy::~IntercomProxy()
{
    //m_server->close();
    //m_server->deleteLater();
    //m_cliMap.clear();
}

void IntercomProxy::listen()
{
    if(Q_NULLPTR == m_server)
    {
        return;
    }

    QString strLog;
    bool blisten  = m_server->listen(m_listenPort);
    if(false == blisten)
    {
        ERROR_PRINT<<"m_server listen "<<m_listenPort<<"  error!";
        strLog.sprintf("m_server listen:%d error!",m_listenPort);
        logFile::printLog(strLog);
        return;
    }

    DEBUG_PRINT<<"m_server listen "<<m_listenPort<<"success!";
    strLog.clear();
    strLog.sprintf("m_server listen:%d success!",m_listenPort);
    logFile::printLog(strLog);
}

void IntercomProxy::onGetOpenDoorData(QString strHttpKey,QByteArray data)
{
    if(strHttpKey != QString("IntercomProxy"))
    {
        return;
    }

    QString strLog;

    //验证源合法性
    QString strSourceData = data;
    QString strHead = QString(")!)@*o#($(");
    int nBegin = strSourceData.indexOf(strHead,0);
    if(0 != nBegin)
    {
        strLog.sprintf("recv illegal data source: %s!",strSourceData.toStdString().c_str());
        logFile::printLog(strLog);
        return;
    }

    nBegin += strHead.size();
    int nValidCount = strSourceData.size() - nBegin;
    QString strValid = strSourceData.right(nValidCount);
    QByteArray validData = strValid.toUtf8();
    QJsonParseError jsonErr;
    QJsonObject jsonObj;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(validData, &jsonErr);
    if (jsonErr.error != QJsonParseError::NoError && !jsonDoc.isObject())
    {
        WARNING_PRINT << "recv unkown msg" << validData << jsonErr.error;
        strLog.clear();
        strLog.sprintf("recv unkown msg Json error: %s, errcode:%d, size = %d",validData.toStdString().c_str(), jsonErr.error, validData.size());
        logFile::printLog(strLog);
        return ;
    }

    jsonObj = jsonDoc.object();

    emit textRecv(validData);

    DEBUG_PRINT << "recv src msg from intercom:" << validData;
    strLog.clear();
    strLog.sprintf("recv src msg from intercom: %s",validData.toStdString().c_str());
    logFile::printLog(strLog);

    QString strMac = jsonObj["mac"].toString();
    QString strIPC_IP = jsonObj["ipc_ip"].toString();
    DEBUG_PRINT << "open door ------: "<<jsonObj["openMode"].toInt()<<validData;

    //emit sigOpenDoor(validData,strMac,strIPC_IP);
    emit sigOpenDoor(validData);

    return;
}
